<template>
    <el-card class="box-card card-item mb-5 border-1" shadow="never" :body-style="{ padding: '20px' }">
        <!-- card body -->
        <div class="flex items-center">
            <el-text class="mr-2">标签名称</el-text>
            <el-input v-model="searchTagName" placeholder="请输入（模糊查询）" style="width: 200px" class="mr-3"/>

            <el-text class="mr-2">创建日期</el-text>
            <el-date-picker v-model="pickDate" type="daterange" range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间" :shortcuts="shortcuts" size="default" @change="datepickerChange"
                        style="width: 260px"/>

            <el-button type="primary" :icon="Search" @click="getTableData" class="ml-9">查询</el-button>
            <el-button :icon="RefreshRight" @click="reset" class="ml-3">重置</el-button>
        </div>
    </el-card>

    <el-card class="box-card card-item border-1" shadow="never">
        <!-- card body -->
        <!-- 新增按钮 -->
        <div class="flex justify-between">
            <div>
                <el-button type="primary" @click="showTagDialog()">
                    <el-icon class="mr-1">
                        <Plus />
                    </el-icon>
                    新增
                </el-button>
                <el-button type="danger" @click="batchDeleteSubmit()" :disabled="!selectedRows.length">
                    <el-icon class="mr-1">
                        <Delete />
                    </el-icon>
                    批量删除
                </el-button>
            </div>
        </div>

        <el-table :data="tableData" stripe style="width: 100%" class="mt-4" v-loading="tableLoading" 
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column prop="tagId" label="ID" width="180" />
            <el-table-column prop="name" label="名称" width="180">
                <template #default="scope">
                    <el-tag class="ml-2" type="info">{{ scope.row.name }}</el-tag>
                </template>

            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="showTagDialog(scope.row)" class="mr-2">
                        <el-icon class="mr-1">
                            <Edit />
                        </el-icon>
                        编辑
                    </el-button>
                    <el-button type="danger" size="small" @click="batchDeleteSubmit([scope.row])">
                        <el-icon class="mr-1">
                            <Delete />
                        </el-icon>
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="mt-5 flex item-center justify-center">
            <el-pagination v-model:current-page="current" v-model:page-size="size" :page-sizes="[10, 20, 50]"
                :small="small" :disabled="disabled" background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="total" @size-change="handleSizeChange" @current-change="getTableData" />
        </div>
    </el-card>

    <!-- 标签表单弹窗 -->
    <el-dialog v-model="isTagDialogShow" :title="dialogTitle" width="30%" :show-close="false" draggable>
        <el-form :model="form" ref="formRef" label-position="top" :size="large" :rules="rules">
            <template v-if="!form.tagId">
                <el-form-item label="" prop="title">
                    <el-tag v-for="tag in dynamicTags" :key="tag" class="mx-1 mb-2" closable :disable-transitions="false"
                        @close="handleClose(tag)" type="info" round>
                        {{ tag }}
                    </el-tag>
                    <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="ml-1 w-20 mb-2" size="small"
                        @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
                    <el-button v-else class="button-new-tag ml-1 mb-2" size="small" @click="showInput" round>
                        + 新增标签
                    </el-button>
                </el-form-item>
            </template>
            <template v-else>
                <el-form-item label="标签名称" prop="name">
                    <el-input v-model="form.name" autocomplete="off" size="large" maxlength="10" show-word-limit clearable/>
                </el-form-item>
            </template>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="handleSubmit">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { addTags, getTagPageList, deleteTag,updateTag } from '@/api/admin/tag'
import { showMessage } from '@/composables/util'
import moment from 'moment';
import { Search, RefreshRight } from '@element-plus/icons-vue'

const isTagDialogShow = ref(false)
const dialogTitle = computed(() => form.tagId ? '编辑标签' : '新增标签')

const searchTagName = ref('')
const pickDate = ref('')
const startDate = reactive({})
const endDate = reactive({})

const reset = () => {
    pickDate.value = ''
    startDate.value = null
    endDate.value = null
    searchTagName.value = ''
}

const datepickerChange = (e) => {
    startDate.value = moment(e[0]).format('YYYY-MM-DD HH:mm:ss')
    endDate.value = moment(e[1]).format('YYYY-MM-DD HH:mm:ss')
}

const shortcuts = [
    {
        text: '最近一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: '最近一个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        },
    },
    {
        text: '最近三个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        },
    },
]

const form = reactive({
    tagId: '',
    name: '',
    tags: []
})

const inputValue = ref('')
const dynamicTags = ref([])
const inputVisible = ref(false)

const handleClose = (tag) => {
    dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
        // InputRef.value!.input!.focus()
    })
}

const handleInputConfirm = () => {
    if (inputValue.value) {
        dynamicTags.value.push(inputValue.value)
    }
    inputVisible.value = false
    inputValue.value = ''
}

const showTagDialog = (row = null) => {
    resetForm()
    if (row) {
        form.tagId = row.tagId
        form.name = row.name
    }
    isTagDialogShow.value = true
}

const closeDialog = () => {
    isTagDialogShow.value = false
    resetForm()
}

const resetForm = () => {
    form.tagId = ''
    form.name = ''
    form.tags = []
    dynamicTags.value = []
    inputValue.value = ''
    inputVisible.value = false
}

const handleSubmit = () => {
    if (form.tagId) {
        // 编辑标签
        updateTag(form).then((e) => {
            if (e.success == false) {
                showMessage(e.message, 'warning', 'message')
                return
            }
            showMessage('修改成功', 'success', 'message')
            closeDialog()
            getTableData()
        })
    } else {
        // 新增标签
        form.tags = dynamicTags.value
        addTags(form).then((e) => {
            if (e.success == false) {
                showMessage(e.message, 'warning', 'message')
                return
            }
            showMessage('添加成功', 'success', 'message')
            closeDialog()
            getTableData()
        })
    }
}

const tableLoading = ref(false)
const tableData = ref([])
// 当前页码
const current = ref(1)
const total = ref(0)
const size = ref(10)

// 获取分页数据
function getTableData() {
    console.log('获取分页数据')
    tableLoading.value = true
    getTagPageList({ current: current.value, size: size.value, startDate: startDate.value, endDate: endDate.value, name: searchTagName.value })
        .then((res) => {
            if (res.success == true) {
                tableData.value = res.data.records
                current.value = res.data.current
                total.value = res.data.total
                size.value = res.data.size
            }
        }).finally(() => {
            tableLoading.value = false
        })
}
getTableData()

const handleSizeChange = (e) => {
    console.log('选择的页码' + e)
    size.value = e
    getTableData()
}

// 添加选择行相关的变量和方法
const selectedRows = ref([])

const handleSelectionChange = (rows) => {
    selectedRows.value = rows
}

// 批量删除提交
const batchDeleteSubmit = (rows) => {
    const deleteRows = rows || selectedRows.value
    if (deleteRows.length === 0) {
        showMessage('请选择要删除的标签', 'warning')
        return
    }

    ElMessageBox.confirm(
        `是否确认要删除选中的 ${deleteRows.length} 个标签?`,
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            const ids = deleteRows.map(row => row.tagId)
            // 修改为传递对象
            deleteTag({data: ids}).then((e) => {
                if (e.success == true) {
                    showMessage('删除成功', 'success')
                    getTableData()
                } else {
                    showMessage(e.message, 'warning')
                }
            })
        })
}

</script>

<style scoped>
.card-item + .card-item {
    margin-top: 16px;
}

.el-pagination {
    margin-top: 20px;
}

/* 确保所有控件在同一行且垂直居中 */
.flex.items-center {
  display: flex !important;
  align-items: center !important;
  min-height: 40px !important;
}

/* 日期选择器样式 */
:deep(.el-date-editor.el-input__wrapper) {
  margin-right: 36px !important;
  display: flex !important;
  align-items: center !important;
  height: 32px !important;
  width: 260px !important;
}

.el-input {
  margin-right: 24px !important;
}

.el-text {
  margin-right: 12px !important;
}

/* 确保按钮有足够的左边距 */
.el-button.ml-9 {
  margin-left: 36px !important;
}

/* 如果上面的选择器不够具体，可以尝试这个 */
.box-card :deep(.el-date-editor.el-input__wrapper),
.box-card :deep(.el-date-picker) {
  width: 260px !important;
  max-width: 260px !important;
}
</style>